<!DOCTYPE html>
<html lang="en">
    <head>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="">
        <meta name="author" content="">

        <title>Kura's Hardware Shop</title>

        <!-- Bootstrap Core CSS -->
        <link href="css/bootstrap.min.css" rel="stylesheet">

        <!-- MetisMenu CSS -->
        <link href="css/plugins/metisMenu/metisMenu.min.css" rel="stylesheet">

        <!-- Custom CSS -->
        <link href="css/sb-admin-2.css" rel="stylesheet">

        <!-- Custom Fonts -->
        <!--link href="font-awesome-4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"-->
		<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
		
		<!-- Suggest panel -->
		<link rel = "stylesheet" type = "text/css" href = "css/style.css" />
		
		<!-- DataTables CSS -->
        <link href="css/plugins/dataTables.bootstrap.css" rel="stylesheet">

        <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
        <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
        <!--[if lt IE 9]>
            <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
            <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
        <![endif]-->

		<!-- jQuery -->
        <script src="js/jquery-2.1.1.min.js"></script>

        <!-- Bootstrap Core JavaScript -->
        <script src="js/bootstrap.min.js"></script>

        <!-- Metis Menu Plugin JavaScript -->
        <script src="js/plugins/metisMenu/metisMenu.min.js"></script>

        <!-- Custom Theme JavaScript -->
        <script src="js/sb-admin-2.js"></script>

		<!-- Suggest script -->
        <script type = 'text/javascript' src= 'js/script.js'></script>
		
		<!-- DataTables JavaScript -->
		<script type = 'text/javascript' src="js/plugins/dataTables/jquery.dataTables.js"></script>
		<script type = 'text/javascript' src="js/plugins/dataTables/dataTables.bootstrap.js"></script>

    </head>

    <body>
        <?php
		@require('script/dbconnect.php');
		date_default_timezone_set('Asia/Ho_Chi_Minh');
        session_start();
        if (!isset($_SESSION['role'])) {
            header("Location: login.php");
        }
        ?>
		
        <div id="wrapper">

            <!-- Navigation -->
            <nav class="navbar navbar-default navbar-static-top" role="navigation" style="margin-bottom: 0">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        <span class="sr-only">Toggle navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" href="index.html">Xin chào <?php echo $_SESSION['name'] ?></a> <!-- get User late -->
                </div>
                <!-- /.navbar-header -->

                <ul class="nav navbar-top-links navbar-right">

                    <li class="dropdown">
                        <a class="dropdown-toggle" data-toggle="dropdown" href="#">
                            <i class="fa fa-user fa-fw"></i>  <i class="fa fa-caret-down"></i>
                        </a>
                        <ul class="dropdown-menu dropdown-user">
                            <li><a href="info.php"><i class="fa fa-user fa-fw"></i> Thông tin cá nhân</a>
                            </li>

                            <li class="divider"></li>
                            <li><a href="script/logoutScript.php"><i class="fa fa-sign-out fa-fw"></i> Đăng xuất</a>
                            </li>
                        </ul>
                        <!-- /.dropdown-user -->
                    </li>
                    <!-- /.dropdown -->
                </ul>
                <!-- /.navbar-top-links -->

                <div class="navbar-default sidebar" role="navigation">
                    <div class="sidebar-nav navbar-collapse">
                        <ul class="nav" id="side-menu">
                            <?php
                            if ($_SESSION['role'] == 1) {
                                ?>
                                <li>
                                    <a class="active" href="statistic.php"><i class="fa fa-bar-chart-o fa"></i> &nbspThống kê<span class="fa arrow"></span></a>
                                    <ul class="nav nav-second-level">
                                        <li>
                                            <a href="statistic.php">Doanh thu</a>
                                        </li>
                                    </ul>
                                </li>

                                <li>
                                    <a href="users.php"><i class="fa fa-user fa-fw"></i> Quản lí nhân viên</a>

                                    <!-- /.nav-second-level -->
                                </li>
                                <?php
                            }
                            ?>
                            <li>
                                <a href="customers.php"><i class="fa fa-wrench fa-fw"></i>&nbsp;Quản lí khách hàng</a>

                                <!-- /.nav-second-level -->
                            </li>
                            <li>
                                <a href="#"><i class="fa fa-shopping-cart fa-fw"></i> Quản lí sản phẩm<span class="fa arrow"></span></a>
                                <ul class="nav nav-second-level">
                                    <li>
                                        <a href="categories.php">Danh mục</a>
                                    </li>
                                    <li>
                                        <a href="manufacturers.php">Nhà sản xuất</a>
                                    </li>                                    
                                    <li>
                                        <a href="products.php">Sản phẩm</a>
                                    </li>
                                </ul>
                            </li>
                            <li>

                                <a href="#"><i class="fa fa-edit fa-fw"></i> Quản lí đơn hàng<span class="fa arrow"></span></a>
                                <ul class="nav nav-second-level">
                                    <li>
                                        <a href="orders_in.php">Hóa đơn nhập</a>
                                    </li>
                                    <li>
                                        <a href="orders_out.php">Hóa đơn xuất</a>
                                    </li>

                                </ul>
                            </li>
                        </ul>
                        <!-- /.nav-second-level -->
                    </div>
                    <!-- /.sidebar-collapse -->
                </div>
                <!-- /.navbar-static-side -->
            </nav>

            <!-- Page Content -->
            <div id="page-wrapper">
                <div class="row">
                    <div class="col-lg-12">
                        <h1 class="page-header">Quản lý hóa đơn xuất</h1>
                    </div>
                    <!-- /.col-lg-12 -->
                </div>
                <!-- /.row 1 -->
				<ul class="nav nav-tabs" role="tablist">
					<li class="active"><a id="tab-header_new-record"  href="#tab_new-record" data-toggle="tab">Nhập mới</a></li>
					<li><a id="tab-header_data" href="#tab_data" data-toggle="tab">Dữ liệu xuất hàng</a></li>
				</ul>
				
				<div class="row">
					<div class="col-lg-12">
						<div class="tab-content">
							<div id="tab_new-record" class="tab-pane active">
								<br>
								<div class="panel panel-default">
									<div class="panel-body">
										<form role="form" id="_orders_form" action = "<?php echo $_SERVER['PHP_SELF'] ?>" method = "POST" autocomplete="off" onSubmit="return validateInput();">
											<div class="row">
												<div class="col-lg-12" id="alert-message">
												</div>
											</div>
											<div class="row">
												<div class="col-lg-9">
													<input name='orders_customer' class="form-control" placeholder="Khách hàng" onKeyUp="loadSuggest(this, 'customer');">
												</div>
												<div class="col-lg-3">
													<input name='orders_time' class="form-control" placeholder="Thời gian" value="<?php echo date('H:i:s d/m/Y'); ?>">
												</div>
												
											</div>
											<br>
											<div class="row">
												<div class="col-lg-12">
													<div class="table-responsive">
														<table class="table table-bordered table-hover" id="DataTable-input" style="table-layout: fixed;">
															<thead>
																<tr>
																	<th class='col-lg-6'>Sản phẩm</th>
																	<th class='col-lg-1'>SL</th>
																	<th class='col-lg-2'>Đơn giá (VNĐ)</th>
																	<th class='col-lg-1'>KM (%)</th>
																	<th class='col-lg-2'>Thành tiền (VNĐ)</th>
																</tr>
															</thead>
																
															<tbody id="_orders-details">
																<tr>
																	<td><input name='orders-details_product[]' class="form-control _product" onKeyUp="loadSuggest(this, 'product');" onFocus="productInputOnchange(this);" onChange="productInputOnchange(this);"></td>
																	<td><input name='orders-details_quantity[]' class="form-control" type="number" min=1 value=1 onChange="productQuantityOnchange(this);"></td>
																	<td><p class="form-control-static _prod_price">---</p></td>
																	<td><input name='orders-details_sale-off[]' class="form-control" type="number" min=0 max=100 value=0 onChange="productQuantityOnchange(this);"></td>
																	<td><p class="form-control-static _prod_total-price">---</p><input name="orders-details_product_total-price[]" class="_prod_total-price" value=0 type=hidden></td>
																</tr>

															</tbody>
															<!-- tbody -->
														</table>
														<!-- /.table .table-striped ... -->
													</div>
													<!-- /.table-responsive -->
												</div>
												<!-- /.col-lg-12 -->
											</div>
											<!-- /.row -->
											
											<div class="row">
												<div class='col-lg-6'>
													<b>Tổng tiền:</b> <span id="order_total">0 VNĐ</span> <input name="row-num" style="display:none" value=1>
												</div>
												<div class='col-lg-6' align='right'>
													<button id="bReset" class="btn btn-default" type="reset">Xóa hết</button>
													<button id="bAddRow" class="btn btn-default" type="button">Thêm dòng</button>
													<button id="bSave" class="btn btn-primary" type="submit">Lưu</button>
												</div>
											</div>
										</form>
									</div>
									<!-- /.panel-body -->
								</div>
								<!-- /.panel .panel-default -->
							</div>
							<!-- /#tab_new-record -->
		
							<script type = 'text/javascript'>
								function priceFormat_VND(money_amount) {
									var str = "";
									var count = 0;
									var tmp = money_amount + "";
									for (var i = tmp.length-1; i >= 0; i--) {
										if (count == 3) {
											count = 0;
											str += " ,";
										}
										str += tmp.charAt(i);
										count++;
										
									}
									return str.split("").reverse().join("");
								}
								
								function getAmount_VND(money_string) {
									return money_string.split(", ").join("");
								}
								
								/*
									The last <> is considered to bound the ID
									An ID-non-parsable string will produce a empty ID string ("")
								*/
								function getID(str){
									// search for the last '>', from there, search for the first '<', get substring
									for (var i = str.length-1; i >= 0; i--) {
										if (str.charAt(i) === '>') {
											for (var j = i; j >= 0; j--) {
												if (str.charAt(j) === '<') {
													return str.substring(j+1, i);
												}
											}
											break;
										}
									}
									return "";
								}
								
								function validateInput() {
									/*
										Customer:
										1. ID-Parsable string: true if !== "", false if === ""
										2. Correct ID
									*/
									var cust = $("input[name='orders_customer']").val();
									var id = getID(cust);
									
									// 1
									if (id === "") {
										$("#alert-message").html("<div class='alert alert-danger' role='alert'>Thiếu thông tin khách hàng!</div>");
										return false;
									}
									
									// 2
									$.getJSON("script/loadSuggest.php", {"text": id, "type": "customer", "context": "validateInput"}, function(data) {
										
										if (data.status === 'success') {
											if (data.suggest.length == 0) {
												$("#alert-message").html("<div class='alert alert-danger' role='alert'>ID khách hàng không khớp với dữ liệu!</div>");
												return false;
											}
										} else {
											alert(data.message);
										}
									});
									
									// total price > 0
									var totalPrice = $('#order_total').text();
									if (totalPrice === "0 VNĐ") {
										$("#alert-message").html("<div class='alert alert-danger' role='alert'>Hóa đơn rỗng!</div>");
										return false;
									}
									
									// Preprocess IDs
									$("input[name='orders_customer']").val(id);
									
									$("input[name='orders-details_product_total-price[]']").each(function(){
										var row = $(this).parent().parent();
										var cells = row.children();
										var text = cells.children("input[name='orders-details_product[]']").val();
										cells.children("input[name='orders-details_product[]']").val(getID(text));
									});
									
									return true;
								}
								
								function productInputOnchange(obj){
									var row = $(obj).parent().parent();
									var cells = row.children();
									var text = obj.value;
									var id = getID(text);
									if (id !== "") {
		
										$.getJSON("script/loadSuggest.php", {"text": id, "type": "product", "context": "productInputOnchange"}, function(data) {
											cells.children("._prod_price").text('---');
											cells.children("._prod_total-price").text('---');
											cells.children("input[name='orders-details_product_total-price[]']").val('0');
											
											if (data.status === 'success') {
												var info = data.suggest[0];
												cells.children("._prod_price").text(priceFormat_VND(info['price']));
												
												var quan = cells.children("input[name='orders-details_quantity[]']").val();
												var sale_off = cells.children("input[name='orders-details_sale-off[]']").val();
												var price = parseInt(info['price']);
												
												if (quan !== "" && sale_off !== "") {
													quan = parseInt(quan);
													sale_off = parseInt(sale_off);
													
													var final_price = price * quan * (1 - (sale_off/100));
													final_price = Math.round(final_price);
													
													cells.children("._prod_total-price").text(priceFormat_VND(final_price));
													cells.children("input[name='orders-details_product_total-price[]']").val(final_price);
												}

												orderTotalPriceOnchange();
											} else {
												alert("Failed to get data");
												
												cells.children("._prod_price").text('---');
												cells.children("._prod_sale-off").text('---');
												cells.children("._prod_total-price").text('---');
												cells.children("input[name='orders-details_product_total-price[]']").val('0');
												
												orderTotalPriceOnchange();
											}
										});
									} else {
										cells.children("._prod_price").text('---');
										cells.children("._prod_sale-off").text('---');
										cells.children("._prod_total-price").text('---');
										cells.children("input[name='orders-details_product_total-price[]']").val('0');
										
										orderTotalPriceOnchange();
									}
									
								}
								
								function productQuantityOnchange(obj) {
									var row = $(obj).parent().parent();
									var cells = row.children();
									var quan = cells.children("input[name='orders-details_quantity[]']").val();
									var price = cells.children("._prod_price").text();
									var sale_off = cells.children("input[name='orders-details_sale-off[]']").val();
									
									if (price !== '---' && sale_off !== '' && quan !== '') {
										quan = parseInt(quan);
										price = parseInt(getAmount_VND(price));
										sale_off = parseInt(sale_off);
										
										if (sale_off >= 0 && sale_off <= 100) {

											var final_price = price * quan * (1 - (sale_off/100));
											final_price = Math.round(final_price);

											cells.children("._prod_total-price").text(priceFormat_VND(final_price));
											cells.children("input[name='orders-details_product_total-price[]']").val(final_price);
										}
										
										orderTotalPriceOnchange();
									} else {
										orderTotalPriceOnchange();
									}
								}
								
								function orderTotalPriceOnchange() {
									var total = 0;
									$("input[name='orders-details_product_total-price[]']").each(function(){
										total += parseInt($(this).val());
									});
									$('#order_total').text(priceFormat_VND(total) + " VNĐ");
								}
								<?php
									/*
										INSERT
									*/
									if(isset($_POST['orders_customer'])) {
										if (strlen($_POST['orders_customer']) > 0) {
											$timeString = $_POST['orders_time'];
											$time = DateTime::createFromFormat('H:i:s d/m/Y', $timeString);

											if ($time !== false) {
												$timeString = $time->format('Y-m-d H:i:s');
												$cust_id = $_POST['orders_customer'];
												
												$insert_orders_sql = "INSERT INTO `orders` (`user`, `customer`, `time`) VALUES ({$_SESSION['id']}, $cust_id, '$timeString');";
                                                                                                $select_orders_sql = "SELECT `id` FROM `orders` WHERE `user` = {$_SESSION['id']} AND `customer` = $cust_id AND `time` = '$timeString';";
												
												if (mysqli_query($db, $insert_orders_sql)) {
													if ($result = mysqli_query($db, $select_orders_sql)) {
														
														$row = mysqli_fetch_assoc($result);
														$id = $row['id'];
														mysqli_free_result($result);
														
														foreach ($_POST['orders-details_product_total-price'] as $key => $val) {
															$done = true;
															if ($val != '0') {
																$prod_id = $_POST['orders-details_product'][$key];
																$prod_quan = $_POST['orders-details_quantity'][$key];
																$prod_saleoff = $_POST['orders-details_sale-off'][$key];
																
																$insert_orders_details_sql = "INSERT INTO `orders_details` (`order`, `product`, `quantity`, `sale_off`) VALUES ($id, $prod_id, $prod_quan, $prod_saleoff)";
																
																if (!mysqli_query($db, $insert_orders_details_sql)) {
																	$done = false;
																	$error_str = mysqli_error($db);
																	if (strpos($error_str, "BIGINT UNSIGNED value is out of range") !== false) {
																		$error_str = "Số lượng sản phẩm [ID: $prod_id] hiện tại không đủ đáp ứng đơn hàng";
																	}
																	echo "$('#alert-message').html(\"<div class='alert alert-danger' role='alert'>Không thể thực hiện lưu hóa đơn (Lỗi #3, " . $error_str . ")!</div>\");";
																	
																	// !By using foreign key, table `orders_details`'s corresponding rows will be deleted too
																	// !! But trigger won't fire at this case, so we need to manually delete them
																	// !!! Delete `orders_details` first
																	$delete_orders_sql = "DELETE FROM `orders_details` WHERE `order` = $id; DELETE FROM `orders` WHERE `id` = $id;";
																	
																	if (mysqli_multi_query($db, $delete_orders_sql)) {
																		do {
																			if ($result = mysqli_store_result($db)) {
																				mysqli_free_result($result);
																			}
																		} while (mysqli_next_result($db));
																	} else {
																		echo "$('#alert-message').html(\"<div class='alert alert-danger' role='alert'>Không thể thực hiện khôi phục từ lỗi #3, xin thực hiện xóa dữ liệu thủ công! (Lỗi #4, " . mysqli_error($db) . ")!</div>\");";
																	}

																	break;
																} // ! insert_orders_details_sql
															}
															
															if ($done) {
																echo "$('#alert-message').html(\"<div class='alert alert-success' role='alert'>Hóa đơn đã được lưu</div>\");";
															}
														} // loop through 'orders-details_product_total-price' array
														
													} else {
														echo "$('#alert-message').html(\"<div class='alert alert-danger' role='alert'>Không thể thực hiện lưu hóa đơn (Lỗi #2, " . mysqli_error($db) . ")!</div>\");";
														
													} // select_orders_sql
													
												} else {
													echo "$('#alert-message').html(\"<div class='alert alert-danger' role='alert'>Không thể thực hiện lưu hóa đơn (Lỗi #1, " . mysqli_error($db) . ")!</div>\");";
													
												} // insert_orders_sql
												
											} // Valid time string 
											else {
												echo "$('#alert-message').html(\"<div class='alert alert-danger' role='alert'>Lỗi #0, Sai định dạng ngày tháng: {hh:mm:ss dd/mm/yyyy}</div>\");";
											}
										} // Valid ID
									} // Form is submitted
							?>
							</script>
							<div id="tab_data" class="tab-pane">
								<br>
								<div class="panel panel-default">
									<div class="panel-body">
										<div class="row">
											<div class="col-lg-12" id="records_alert-message">
											</div>
										</div>
										<script>
														<?php
															if (isset($_POST['bDel'])) {
																$_id = $_POST['bDel'];
																$del_sql = "DELETE FROM `orders_details` WHERE `order` = $_id; DELETE FROM `orders` WHERE `id` = $_id;";
																if (mysqli_multi_query($db, $del_sql)) {
																	do {
																		if ($result = mysqli_store_result($db)) {
																			mysqli_free_result($result);
																		}
																	} while (mysqli_next_result($db));
																	echo "$('#records_alert-message').html(\"<div class='alert alert-success' role='alert'>Hoàn tất dòng xóa dữ liệu đã chọn</div>\");";
																	echo "$('#tab-header_data').click();";
																} else {
																	echo "$('#records_alert-message').html(\"<div class='alert alert-danger' role='alert'>Không thể dòng xóa dữ liệu đã chọn: " . mysqli_error($db) . "</div>\");";
																}
															}
														?>
										</script>
										<form role="form" action = "<?php echo $_SERVER['PHP_SELF'] ?>" method = "POST" onSubmit="return confirm('Xác nhận xóa dòng dữ liệu đã chọn?');">
										<div class="table-responsive">
											<table class="table table-bordered table-hover" id="DataTable-records" style="table-layout: fixed;">
												<thead>
													<tr>
														<th class='col-lg-2'>Thời gian</th>
														<th class='col-lg-4'>Khách hàng</th>
														<th class='col-lg-2'>Trị giá (VNĐ)</th>
														<th class='col-lg-2'>Người nhập</th>
														<th class='col-lg-2'></th>
													</tr>
												</thead>
												
												<tbody>
													
														<?php	
															$ICON_EDIT 	= "<i class='fa fa-edit fa-fw'></i>";
															$ICON_TRASH = "<i class='fa fa-trash fa-fw'></i>";
															$ICON_EYE 	= "<i class='fa fa-eye fa-fw'></i>";
															
															function priceFormat_VND($money_amount) {
																$vnd = number_format($money_amount, 0, '.', ', ');
																return $vnd;
															}
															
															$sql = "SELECT `orders`.`id` as `id`, TRUNCATE(SUM(`orders_details`.`quantity` * `products`.`price` * (1-(`orders_details`.`sale_off`/100))), 0) as `total_price`, `customers`.`id` as `cust_id`, `customers`.`name` as `cust_name`, `customers`.`address` as `cust_addr`, `customers`.`phone` as `cust_phone`, `customers`.`email` as `cust_email`, `users`.`id` as `user_id`, `users`.`name` as `user_name`, `users`.`address` as `user_addr`, `users`.`phone` as `user_phone`, `users`.`email` as `user_email`, `users`.`gender` as `user_gend`, `users`.`id_number` as `user_idno`, `users`.`role` as `user_role`, `users`.`birthday` as `user_birthday`, `time` FROM `orders`, `customers`, `users`, `orders_details`, `products` WHERE `orders`.`customer` = `customers`.`id` AND `orders`.`user` = `users`.`id` AND `orders`.`id` = `orders_details`.`order` AND `orders_details`.`product` = `products`.`id` GROUP BY `orders`.`id`;";
															
															if ($result = mysqli_query($db, $sql)) {
																while ($row = mysqli_fetch_assoc($result)) {
																	$_gender = ($row['user_gend'] == 1)? "Nam": "Nữ";
																	$_role = ($row['user_role'] == 1)? "admin": "nhân viên";
																	$_order_time = date('H:i:s d/m/Y', strtotime($row['time']));
																	$_user_birthday = date('d/m/Y', strtotime($row['user_birthday']));
																	$_price = priceFormat_VND($row['total_price']);
																	
																	$cust_info = "<b>Địa chỉ:</b> {$row['cust_addr']}<br>
																				<b>Điện thoại:</b> {$row['cust_phone']}<br>
																				<b>Email:</b> {$row['cust_email']}";
																	
																	$user_info = "<b>Giới tính:</b> $_gender<br>
																				<b>CMND:</b> {$row['user_idno']}<br>
																				<b>Ngày sinh:</b> $_user_birthday<br>
																				<b>Địa chỉ:</b> {$row['user_addr']}<br>
																				<b>Điện thoại:</b> {$row['user_phone']}<br>
																				<b>Email:</b> {$row['user_email']}";
																	echo "<tr>
																			<td class='_order_time'>$_order_time</td>
																			
																			<td class='_order_cust' data-toggle='popover' title=\"Dữ liệu khách hàng <{$row['cust_id']}>\" data-content='$cust_info'>{$row['cust_name']}</td>
																			
																			<td>$_price</td>
																			
																			<td data-toggle='popover' title='Dữ liệu $_role [ID: {$row['user_id']}]' data-content='$user_info'>
																				{$row['user_name']}
																			</td>
																			
																			<td align=center>
																				<button name='bEdit' value='{$row['id']}' type='button' class='btn btn-link' data-toggle='modal' data-target='#modal-modify' title='Sửa'>
																					{$ICON_EDIT}
																				</button>
																				<button name='bDel' value='{$row['id']}' type='submit' class='btn btn-link' title='Xóa'>
																					{$ICON_TRASH}
																				</button>
																				<button name='bView' value='{$row['id']}' type='button' class='btn btn-link' data-toggle='modal' data-target='#modal-details' title='Xem chi tiết'>
																					{$ICON_EYE}
																				</button>
																			</td>
																		 </tr>";
																}
																mysqli_free_result($result);
															} else {
																echo "<p>Failed to get data: " . mysqli_error($db) . "</p>";
															}
														?>
													
												</tbody>
												<!-- tbody -->
												
											</table>
											<!-- /#DataTable-records .table .table-striped ... -->
										</div>
										<!-- /.table-responsive -->
										</form>
									</div>
									<!-- /.panel-body -->
								</div>
								<!-- /.panel .panel-default -->
							</div>
							<!-- /#tab_data -->
						</div>
						<!-- /#.tab-content -->						
                    </div>
                    <!-- /.col-lg-12 -->
                </div>
                <!-- /.row 2 -->
            </div>
            <!-- /#page-wrapper -->

        </div>
        <!-- /#wrapper -->
		
		<!-- Modal modify -->
        <div class="modal fade bs-example-modal-lg" id="modal-modify" tabindex="-1" role="dialog" aria-labelledby="modal-modify_label" aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                        <h4 class="modal-title" id="modal-modify_label">Chỉnh sửa hóa đơn xuất hàng</h4>
                    </div>
                    <div class="modal-body">
						<div class='row'>
							<div class='col-md-12' id = "modal-modify_alert-box">
								
							</div>
						</div> <!-- / .row -->
						<div class='row'>
							<div class='col-md-8'>
								<input id="order-modify__customer" class="form-control" onKeyUp="loadSuggest(this, 'customer');" placeholder="Khách hàng" type=text>
							</div>
							<div class='col-md-4'>
								<input id="order-modify__time" class="form-control" placeholder="Thời gian" type=text>
							</div>
						</div> <!-- / .row -->
						<br>
                        <div class='row'>
                            <div class='col-md-12'>
								<div class="table-responsive">
									<table class="table table-bordered table-hover" id="DataTable_modal-modify" style="table-layout: fixed;">
															<thead>
																<tr>
																	<th class='col-md-4'>Sản phẩm</th>
																	<th class='col-md-2'>Số lượng</th>
																	<th class='col-md-2'>Đơn giá (VNĐ)</th>
																	<th class='col-md-2'>KM (%)</th>
																	<th class='col-md-2'>Thành tiền (VNĐ)</th>
																</tr>
															</thead>
																
															<tbody id="_orders-modify">

															</tbody>
															<!-- tbody -->
									</table> <!-- /.table  -->
								</div> <!-- /.table-responsive -->
                            </div> <!-- /.col-md-12 -->
                        </div> <!-- /.row -->
                    </div> <!-- /. modal-body -->
                    <div class="modal-footer">
						<div class=row>
							<div class='col-md-6' align=left>
								<b>Tổng tiền:</b> <span id="order-modify_total">0 VNĐ</span>
							</div>
							<div class='col-md-6'>
								<button type=button class="btn btn-default" id='modal-modify_act_add-row'>Thêm dòng</button>
								<button type=button class="btn btn-default" data-dismiss="modal">Đóng</button>
								<button type=button class="btn btn-primary" id="modal-modify_act_save">Lưu</button>
							</div>
						</div>
                    </div>
                </div>
            </div>
        </div>
		<!-- /#modal_modify -->
		
		<!-- Modal -->
        <div class="modal fade bs-example-modal-lg" id="modal-details" tabindex="-1" role="dialog" aria-labelledby="modal-details_label" aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                        <h4 class="modal-title" id="modal-details_label">Xem chi tiết hóa đơn xuất hàng</h4>
                    </div>
                    <div class="modal-body">
								<div class='row'>
									<div class='col-md-12'>
										<div class="table-responsive">						
											<table class="table table-bordered table-hover" id="DataTable_modal-details" style="table-layout: fixed;">
												<thead>
													<tr>
														<th class='col-md-8'>Sản phẩm</th>
														<th class='col-md-1'>Số lượng</th>
														<th class='col-md-3'>Thành tiền (VNĐ)</th>
													</tr>
												</thead>
														
												<tbody id="modal-details_content">
															
												</tbody> <!-- tbody -->
											</table> <!-- /#DataTable-records -->

										</div> <!-- /.table-responsive -->
									</div> <!-- /. col-md-12 -->
								</div> <!-- ./row -->

                    </div> <!-- /. modal-body -->
                    <div class="modal-footer">
                        <button type=button class="btn btn-primary" data-dismiss="modal">Đóng</button>
                    </div>
                </div>
            </div>
        </div>
		<!-- /#modal_details -->
		
		<!-- Suggest panel -->
		<div id = "__suggest-panel_popup"></div>
		
		<script type = 'text/javascript'>
								$(document).ready(function() {
									$('[data-toggle="popover"]').popover({trigger: 'hover','placement': 'top', 'html': true, 'container': 'body'});
									$('#DataTable-records').dataTable();
									var dataTableModalDetails = $('#DataTable_modal-details').DataTable();
									$('#bReset').on('click', function(){
										$('._prod_price').text("---");
										$('._prod_sale-off').text("---");
										$('._prod_total-price').text("---");
										$("input[name='orders-details_product_total-price[]'").val("0");
										$('#order_total').text("0 VNĐ");
									});
									$('#bAddRow').on('click', function(){
										$('#_orders-details').append("<tr><td><input name='orders-details_product[]' class='form-control _product' onKeyUp=\"loadSuggest(this, 'product');\" onFocus=\"productInputOnchange(this);\" onChange=\"productInputOnchange(this);\"></td><td><input name='orders-details_quantity[]' class='form-control _prod_quan' type='number' min=1 value=1 onChange='productQuantityOnchange(this);'></td><td><p class='form-control-static _prod_price'>---</p></td><td><input name='orders-details_sale-off[]' class='form-control' type='number' min=0 max=100 value=0 onChange=\"productQuantityOnchange(this);\"></td><td><p class='form-control-static _prod_total-price'>---</p><input name='orders-details_product_total-price[]' class='_prod_total-price' value=0 type=hidden></td></tr>");
									});
									$('#bSave').on('click', function() {
										
									});
									$("button[name='bView']").on('click', function() {
									
										var id = $(this).val();
										dataTableModalDetails.clear();

										$.getJSON("script/loadSuggest.php", {"text": id, "type": "order", "context": "bView"}, function(data) {
											if (data.status == 'success') {
												
												$.each(data.suggest, function(key, val){
													var info = data.suggest[key];
													var prod_info = "<b>Giá:</b> " + priceFormat_VND(info['price']) + " VNĐ<br><b>Số lượng còn:</b> " + info['prod_quan'] + "<br>" + info['category'] + "<br>" + info['manufacturer'];
													dataTableModalDetails.row.add([
														"<div data-toggle='popover' title='Dữ liệu sản phẩm [ID: " + info['id'] + "]' data-content='" + prod_info + "'>" + info['name'] + "</div>", 
														info['order_quan'], 
														priceFormat_VND(info['order_price'])
													]).draw();
												});
												
												$('[data-toggle="popover"]').popover({trigger: 'hover','placement': 'top', 'html': true, 'container': 'body'});
											} else {
												alert("Failed to get data: " + data.message);
											}
										});
									});
									
									$("button[name='bEdit']").on('click', function() {
										var id = $(this).val();
										var row = $(this).parent().parent();
										
										$("#order-modify__customer").val(
											row.children('._order_cust').text() 
											+ " <" + getID(
												row.children('._order_cust').attr('data-original-title')
											) + ">"
										);
										$("#order-modify__time").val(row.children('._order_time').text());
										$("#order-modify__customer").parent().append("<input type=hidden name='_order_id' value='" + id + "'>");
										
										var output = $("#_orders-modify");
										$.getJSON("script/loadSuggest.php", {"text": id, "type": "order", "context": "bEdit"}, function(data) {
											if (data.status == 'success') {
												var str = "";
												$.each(data.suggest, function(key, val){
													str += "<tr><td><input name='orders-modify_product[]' class='form-control _product' onKeyUp=\"loadSuggest(this, 'product');\" onFocus=\"productInputOnchange2(this);\" onChange=\"productInputOnchange2(this);\" value='" + val['name'] + " <" + val['id'] + ">" + "'></td><td><input name='orders-modify_quantity[]' class='form-control _prod_quan' type='number' min=1 onChange=\"productQuantityOnchange2(this);\" value='" + val['order_quan'] + "'></td><td><p class='form-control-static _prod_price'>" + priceFormat_VND(val['price']) + "</p></td><td><input name='orders-modify_sale-off[]' class='form-control _prod_quan' type='number' min=0 max=100 onChange=\"productQuantityOnchange2(this);\" value='" + val['sale_off'] + "'></td><td><p class='form-control-static _prod_total-price'>" + priceFormat_VND(val['order_price']) + "</p><input name='orders-modify_product_total-price[]' value=" + val['order_price'] + " type=hidden></td></tr>";
												});
												
												output.html(str);
												orderTotalPriceOnchange2();
											} else {
												alert("Failed to get data: " + data.message);
											}
										});
									});
									
									$("#modal-modify_act_add-row").on('click', function(){
										var output_items = $("#_orders-modify");
										output_items.append("<tr><td><input name='orders-modify_product[]' class='form-control _product' onKeyUp=\"loadSuggest(this, 'product');\" onFocus=\"productInputOnchange2(this);\" onChange=\"productInputOnchange2(this);\"></td><td><input name='orders-modify_quantity[]' class='form-control _prod_quan' type='number' min=1 value=0 onChange=\"productQuantityOnchange2(this);\" ></td><td><p class='form-control-static _prod_price'>---</p></td><td><input name='orders-modify_sale-off[]' class='form-control _prod_quan' type='number' min=0 max=100 onChange=\"productQuantityOnchange2(this);\" value=0></td><td><p class='form-control-static _prod_total-price'>---</p><input name='orders-modify_product_total-price[]' value=0 type=hidden></td></tr>");
									});
									
									save_success = false;
									$("#modal-modify_act_save").on('click', function(){
										var order = $("input[name='_order_id']").val();
										var customer = $("#order-modify__customer").val();
										
										if (getID(customer) !== "") {
											
											customer = getID(customer);
											
											var time = $("#order-modify__time").val();
											var total_price = $("input[name='orders-modify_product_total-price[]']");
											var product = $("input[name='orders-modify_product[]']");
											var quantity = $("input[name='orders-modify_quantity[]']");
											var sale_off = $("input[name='orders-modify_sale-off[]']");
											
											var list = [];
											var listProduct = [];
											var listQuantity = [];
											var listSaleOff = [];
											
											for (var i = 0; i < total_price.length; i++) {
												if (total_price[i].value != 0) {
													list[list.length] = total_price[i].value;
													listProduct[listProduct.length] = getID(product[i].value);
													listQuantity[listQuantity.length] = quantity[i].value;
													listSaleOff[listSaleOff.length] = sale_off[i].value;
												}
											}
											
											$.getJSON("script/table_orders_ajax.php", 
											{
												"order": order, 
												"customer": customer, 
												"time": time, 
												"list": list, 
												"product": listProduct, 
												"quantity": listQuantity,
												"sale_off": listSaleOff
											}, 
											function(data){
												if (data.status == 'success') {
													$("#modal-modify_alert-box").html("<div class='alert alert-success' role='alert'>Cập nhật dữ liệu thành công</div>");
													save_success = true;
												} else {
													$("#modal-modify_alert-box").html("<div class='alert alert-danger' role='alert'>" + data.message + "</div>");
													save_success = false;
												}
											})
											.error(function(xhr, a, b) { 
												alert(xhr.responseText); 
											});
																						
										} else {
											$("#modal-modify_alert-box").html("<div class='alert alert-danger' role='alert'>Dữ liệu khách hàng không hợp lệ</div>");
										}
									});
									
									$('#modal-modify').on('hidden.bs.modal', function () {
										$("#modal-modify_alert-box").html("");
										if (save_success == true) location.reload();
									});
								});

								function productInputOnchange2(obj){
									var row = $(obj).parent().parent();
									var cells = row.children();
									var text = obj.value;
									var id = getID(text);
									if (id !== "") {		
										$.getJSON("script/loadSuggest.php", {"text": id, "type": "product", "context": "productInputOnchange"}, function(data) {
											cells.children("._prod_price").text('---');
											cells.children("._prod_sale-off").text('---');
											cells.children("._prod_total-price").text('---');
											cells.children("input[name='orders-modify_product_total-price[]']").val('0');
											
											if (data.status === 'success') {
												var info = data.suggest[0];
												cells.children("._prod_price").text(priceFormat_VND(info['price']));
												
												var quan = cells.children("input[name='orders-modify_quantity[]']").val();
												var sale_off = cells.children("input[name='orders-modify_sale-off[]']").val();
												var price = parseInt(info['price']);
												
												if (quan !== "" && sale_off !== "") {
													quan = parseInt(quan);
													sale_off = parseInt(sale_off);
													
													var final_price = price * quan * (1 - (sale_off/100));
													final_price = Math.round(final_price);
													
													cells.children("._prod_total-price").text(priceFormat_VND(final_price));
													cells.children("input[name='orders-modify_product_total-price[]']").val(final_price);
												}
												
												orderTotalPriceOnchange2();
												
											} else {
												alert("Failed to get data");
												
												cells.children("._prod_price").text('---');
												cells.children("._prod_sale-off").text('---');
												cells.children("._prod_total-price").text('---');
												cells.children("input[name='orders-modify_product_total-price[]']").val('0');
												
												orderTotalPriceOnchange2();
											}
										});
									} else {
										cells.children("._prod_price").text('---');
										cells.children("._prod_sale-off").text('---');
										cells.children("._prod_total-price").text('---');
										cells.children("input[name='orders-modify_product_total-price[]']").val('0');
										
										orderTotalPriceOnchange2();
									}
									
								}
								
								function productQuantityOnchange2(obj) {
									var row = $(obj).parent().parent();
									var cells = row.children();
									var quan = cells.children("input[name='orders-modify_quantity[]']").val();
									var price = cells.children("._prod_price").text();
									var sale_off = cells.children("input[name='orders-modify_sale-off[]']").val();
									
									if (price !== '---' && sale_off !== '' && quan !== '') {
										quan = parseInt(quan);
										price = parseInt(getAmount_VND(price));
										sale_off = parseInt(sale_off);
										
										if (sale_off >= 0 && sale_off <= 100) {

											var final_price = price * quan * (1 - (sale_off/100));
											final_price = Math.round(final_price);

											cells.children("._prod_total-price").text(priceFormat_VND(final_price));
											cells.children("input[name='orders-modify_product_total-price[]']").val(final_price);
										}
										
										orderTotalPriceOnchange2();
									} else {
										orderTotalPriceOnchange2();
									}
								}
								
								function orderTotalPriceOnchange2() {
									var total = 0;
									$("input[name='orders-modify_product_total-price[]']").each(function(){
										total += parseInt($(this).val());
									});
									$('#order-modify_total').text(priceFormat_VND(total) + " VNĐ");
								}
								<?php
									if (isset($_SESSION['reload']) && $_SESSION['reload'] === true) {
										$_SESSION['reload'] = false;
										echo "$('#tab-header_data').click();";
									}
								?>
							</script>
							
    </body>

</html>